# -*- coding: utf-8 -*-
"""
Created on Tue Jan 27 17:20:13 2015

:History:

@author: azzollini
"""

from __future__ import absolute_import, unicode_literals, division, print_function

from pdb import set_trace as stop

from scipy import special as sp
import numpy as np
from scipy import optimize as op


def k(ns):
    """Returns k(ns)"""
    
    def fk(k,*args):
        #return sp.gamma(2*double(args[0])) * (1.- \
        #2.* sp.gammainc(2.*double(args[0]),k))
	   return sp.gamma(2.*args[0]) * \
	    (sp.gammainc(2.*args[0],k) - 1./2.)
    
    if ns >= 0.5: kprox = 2.*ns - 0.331
    else:
        kprox = (0.699/0.5) * ns
    
    return op.brentq(fk,0.,kprox*3.,args=(ns,))

def fsersic(x,i_e,r_e,ns):
    """Sersic Profile"""
    kthis = k(ns)
    return i_e * np.exp(-kthis*((x/r_e)**(1./ns)-1))
    
    
def fexp(x,i_0,h):
    """Exponential Profile"""
    return i_0 * np.exp(-x/h)


def dist_mask(Pos,Cen,q=1.,pa=0.,c=0.):
    """ """
    
    ang_rad = pa * np.pi / 180. # Convert to radians
    cosang = np.cos(ang_rad)
    sinang = np.sin(ang_rad)
    
    #x = Pos.x - Cen.x
    #y = Pos.y - Cen.y
    
    x = Pos[0] - Cen[0]
    y = Pos[1] - Cen[1]
    
    xrot =  x*cosang + y*sinang
    yrot = -x*sinang + y*cosang
    distance = ( (abs(xrot/q))**(c+2) + (abs(yrot))**(c+2) )**(1/(c+2))

    return distance


def azimuth_mask(Pos,Cen,pa=0.):
    """ """
    
    ang_rad = pa * np.pi / 180. # Convert to radians
    cosang = np.cos(ang_rad)
    sinang = np.sin(ang_rad)
    
    #x = Pos.x - Cen.x
    #y = Pos.y - Cen.y
    x = Pos[0] - Cen[0]
    y = Pos[1] - Cen[1]
 
    
    xrot =  x*cosang + y*sinang
    yrot = -x*sinang + y*cosang
    
    azimuth = np.where(xrot !=0, np.arctan(yrot/xrot),\
        np.pi/2.+np.pi*(1.-(yrot >= 0.).astype('float32')))
    azimuth[np.where((xrot ==0.) & (yrot ==0.))] = 0.
    
    return azimuth
    

# A minimal test is run when this file is run as a main program.
if __name__ == '__main__':
    print("Testing the module\n")
    # Basic code/example test
    print("Test finished.")